package jwei.apps.indextank;

import jwei.apps.indextank.service.LocationProvider;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

public class AppEntry extends Activity {

    private ProgressDialog pd;
    
    private Handler handler = new Handler();
    
    private LocationProvider lp;
    
    private final String LOG_TAG = "AppEntry";
    
    private final int MAX_ATTEMPTS = 5;
    
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_entry_layout);

        // new IndexTask().execute();
        lp = new LocationProvider(AppEntry.this);

        handler.postDelayed(updateStatus, 100);
        pd = ProgressDialog.show(AppEntry.this, "Loading", "Loading... please wait...", true, false);
    }

    private Runnable updateStatus = new Runnable() {

        @Override
        public void run() {
            Location ret = lp.getLocationAndUpdate();
            if (ret == null) {
                // 8 second delay
                Log.i(LOG_TAG, "Checking location...");
                count++;
                if (count < MAX_ATTEMPTS) {
                    handler.postDelayed(this, 1 * 1000);
                } else {
                    Log.i(LOG_TAG, "Could not retrieve location");
                    if (pd.isShowing()) {
                        pd.dismiss();
                    }
                    startActivity(new Intent(AppEntry.this, MainActivity.class));
                    finish();
                }
            } else {
                Log.i(LOG_TAG, "Location retrieved");
                if (pd.isShowing()) {
                    pd.dismiss();
                }
                startActivity(new Intent(AppEntry.this, MainActivity.class));
                finish();
            }

        }

    };

    /*
    private class IndexTask extends AsyncTask<String, String, BatchResults> {

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(AppEntry.this, "Indexing Data", "Please wait while we index your data...", true,
                    false);
        }

        protected BatchResults doInBackground(String... param) {
            IndexTankClient client = new IndexTankClient(Constants.INDEX_URL);
            Index index = client.getIndex(Constants.INDEX_NAME);

            List<Document> documents = new ArrayList<Document>();
            try {
                // index.deleteDocument("c78adfbe-4df9-4ba1-9ee3-1a5133794347");
                // index.deleteDocument("e4b1ffc1-8eb6-455f-8b90-581a6f5ec4c6");

                // csv file containing data
                String strFile = "/sdcard/data_full.csv";

                // create BufferedReader to read csv file
                BufferedReader br = new BufferedReader(new FileReader(strFile));
                String strLine = "";
                String[] st = null;
                int lineNumber = 0;

                // skip first line
                br.readLine();

                // read comma separated file line by line
                while ((strLine = br.readLine()) != null) {
                    lineNumber++;
                    st = strLine.split(",", -1);
                    if (st.length != 10) {
                        continue;
                    }
                    Map<String, String> fields = new HashMap<String, String>();
                    String uid = st[0];
                    fields.put("name", st[1]);
                    String addr = st[2];
                    if (addr.equals("")) {
                        continue;
                    }
                    String city = st[3];
                    String state = st[4];
                    fields.put("address", addr);
                    fields.put("city", city);
                    fields.put("state", state);
                    fields.put("postcode", st[5]);
                    fields.put("telephone", st[6]);
                    fields.put("website", st[7]);
                    String lat = st[8];
                    String lon = st[9];
                    if (lat.equals("") || lon.equals("")) {
                        Location l = GeocoderService
                                .geocode(addr + ", " + city + ", " + state, getApplicationContext());
                        lat = String.valueOf(l.getLatitude());
                        lon = String.valueOf(l.getLongitude());
                        System.out.println(addr + ", " + city + ", " + state + ": (" + lat + "," + lon + ")");
                    }
                    Map<Integer, Float> variables = new HashMap<Integer, Float>();
                    variables.put(0, Float.parseFloat(lat));
                    variables.put(1, Float.parseFloat(lon));

                    // these are additional fields
                    // allows users to query for foods, dishes,
                    // ingredients, etc
                    fields.put("tags", "food");
                    fields.put("dishes", "");
                    fields.put("ingredients", "");
                    Document document = new Document(uid, fields, variables, null);
                    documents.add(document);
                    publishProgress("Finished indexing: " + lineNumber);
                    if (lineNumber % 1500 == 0) {
                        // batch add incrementally
                        index.addDocuments(documents);
                        documents = new ArrayList<Document>();
                    }
                }

                BatchResults results = index.addDocuments(documents);
                return results;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onProgressUpdate(String... progress) {
            pd.setMessage(progress[0]);
        }

        protected void onPostExecute(BatchResults results) {
            // scroll these results in the footer
            if (results == null || results.hasErrors()) {
                Log.e(LOG_TAG, "ERRORS");
            } else {
                Toast t = Toast.makeText(AppEntry.this, "Successfully indexed data!", Toast.LENGTH_SHORT);
                t.show();
            }
            if (pd.isShowing()) {
                pd.dismiss();
            }
        }
    }
    */
    
}
